package com.ruiysoft.service.order.mq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.ruiysoft.conf.mq.OrderMqConfig;
import com.ruiysoft.conf.mq.PayCallBackMqConfig;
import com.ruiysoft.controller.wx.dto.OrderPaidDto;
import com.ruiysoft.service.order.bean.OrderPaymentCallbackDto;
import com.ruiysoft.service.order.facade.OrderPaymentCallbackFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Date : 2018/11/24
 *
 * @author WenJialu
 */
@Component
public class OrderPaymentCallbackSubscriber {

	private final Logger LOGGER = LoggerFactory.getLogger(OrderPaymentCallbackSubscriber.class);

	@Resource
	OrderPaymentCallbackFacade orderPaymentCallbackFacade;

	@RabbitListener(
			bindings = {
					@QueueBinding(
							value = @Queue(value = OrderMqConfig.ORDER_PAYMENT_CALLBACK_QUEUE_NAME,
									durable = "true",
									autoDelete = "false"),
							exchange = @Exchange(value = PayCallBackMqConfig.PAY_CALLBACK_QUANTITY_EXCHANGE, autoDelete = "false"),
							key = PayCallBackMqConfig.PAY_CALLBACK_QUANTITY_BIND_KEY
					)

			}
	)
	@Transactional
	public void onMessage(Message message, Channel channel) throws IOException {
		String json = new String(message.getBody(), StandardCharsets.UTF_8);
		LOGGER.info("支付回调onMessage -->\n" + json);

		OrderPaidDto orderPaidDto = JSON.parseObject(json, OrderPaidDto.class);
		OrderPaymentCallbackDto dto = new OrderPaymentCallbackDto()
				.setResultCode(orderPaidDto.getResultCode())
				.setSysTransactionNo(orderPaidDto.getTransactionNo())
				.setTransactionId(orderPaidDto.getTransactionId())
				.setPayAmount(orderPaidDto.getPayAmount())
				.setErrorMessage(orderPaidDto.getErrorMessage());

		dto = orderPaymentCallbackFacade.paymentCallback(dto);
		if(!dto.isSuccess()){
			//TODO 处理错误"订单支付更新"
		}

		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
	}

	public static void main(String[] args) {
		String json = "{\"orderNo\":\"CP20181124233936072\",\"payAmount\":10,\"payTime\":1543073987000,\"resultCode\":\"SUCCESS\",\"transactionId\":\"4200000224201811240661331112\"}";
        System.out.println(json);
        OrderPaidDto orderPaidDto = JSON.parseObject(json, OrderPaidDto.class);
		System.out.println(orderPaidDto);



	}


}
